package cn.xing.managementSystem.controller;

import cn.xing.managementSystem.bean.ResponseContent;
import cn.xing.managementSystem.commons.Constants;
import cn.xing.managementSystem.domain.SysUser;
import cn.xing.managementSystem.service.SysUserService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @author cuixing
 * @package cn.xing.managementSystem.controller
 * @class SystemController
 * @email xing.cui@magicwindow.cn
 * @date 2018/4/23 下午12:02
 * @description
 */

@Controller
public class SystemController {

    @Value("${credentialsSalt}")
    private String credentialsSalt;

    @Autowired
    private SysUserService sysUserService;

    @RequestMapping("/editPassword")
    public String editPassword(){
        return "content/editPassword";
    }


    @RequestMapping("/savePassword")
    @ResponseBody
    public ResponseContent savePassword(HttpServletRequest request, HttpServletResponse response,
                                        @RequestParam String originalPassword, @RequestParam String newPassword1, @RequestParam String newPassword2){
        SysUser sysUser = (SysUser)request.getSession().getAttribute(Constants.GLOBAL_USER_KEY);
        String encryptStrPassword = DigestUtils.md5Hex(originalPassword + credentialsSalt);
        if(!sysUser.getPassword().equals(encryptStrPassword)){
            return ResponseContent.buildFail("旧密码输入错误！");
        }else if(!newPassword2.equals(newPassword1)){
            return ResponseContent.buildFail("两次输入新密码不一致！！");
        }else{
            String newPassword = DigestUtils.md5Hex(newPassword1 + credentialsSalt);
            sysUser.setPassword(newPassword);
            sysUser = sysUserService.saveSysUser(sysUser);
            request.getSession().setAttribute(Constants.GLOBAL_USER_KEY, sysUser);
            return ResponseContent.buildSuccess("密码修改成功！");
        }

    }
}